/*
* Copyright (C) 2020 ~ 2023 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include <MkRtmp/MkRtmpPublisher.h>
#include <MkUtil/MkLog.h>
#include <MkEvent/MkEventPool.h>
#include <MkEvent/MkTimer.h>
#include <MkMedia/MkFileSource.h>
#include <MkEvent/MkEvent.h>

CMkTimer* g_pTimer = nullptr;
CMkRtmpPublisher* g_pPublisher = nullptr;
int main(int argc, char** argv)
{
    //if (argc < 4) {
    //    printf("Usage:%s 264FileName RtmpUrlBase Count\n", argv[0]);
    //    return 0;
    //}
    //MkString FileName = argv[1];
    //MkString RtmpUrlBase = argv[2];
    //int nCount = std::stoi(argv[3]);

    MkString FileName = "C:/Workspace/media/aa.264";
    MkString RtmpUrlBase = "rtmp://192.168.100.120/live/";
    //MkString RtmpUrlBase = "rtmp://192.168.0.24/live/";
    int nCount = 1;
#ifdef _WIN32
    WSADATA WSAData;
    WSAStartup(0x101, &WSAData);
#endif
    MkLogChangeLevel(LOG_DEBUG);
    MkLogChangeWriteDst(TO_SCREEN);
    CMkEventPool* pEventPool = new CMkEventPool;
    pEventPool->Start();
    CMkTimer *pTimer = new CMkTimer;
    g_pTimer = pTimer;
    pTimer->StartTimerThread();
    CMkMediaSource::SetCachePacket(FALSE);
    int Index = 0;
    MkString RtmpUrl;
    while (Index < nCount) {
        RtmpUrl = RtmpUrlBase + "test" + std::to_string(Index++);
        FILE *fp = fopen(FileName.c_str(), "rb");
        if (nullptr == fp) {
            break;
        }
        CMkH264FileSource *pMediaSource = new CMkH264FileSource(fp, pTimer);
        pMediaSource->ScanFile();
        g_pPublisher = new CMkRtmpPublisher(pEventPool->GetFreeEvent(), pTimer, [pMediaSource](CMkTcpClient* pClient) {
            pMediaSource->StopMediaSource();
            pClient->GetEvent()->AddPipTask([pClient]() {
                delete pClient;
            });
        }, [pMediaSource]() {
            pMediaSource->StartMediaSource(nullptr, [](const MkEsPacket& EsPacket, const CMkVideoParam& VideoParam, const CMkAudioParam& AudioParam) {
                g_pPublisher->SendEsPacket(EsPacket);
                return NoneError;
            });
        });
        g_pPublisher->Start(RtmpUrl, pMediaSource->GetVideoParam(), pMediaSource->GetAudioParam(), pMediaSource->m_FileSize, pMediaSource->m_Duration);
        CMkThread::ThreadSleep(1000);
    }
    while (1) {
        CMkThread::ThreadSleep(10000);
    }
    pTimer->StopTimerThread();
    pEventPool->Stop();
    MkDelete(pEventPool);
    MkDelete(pTimer);
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}